<template>
  <div>
    <!-- 工具栏 -->
    <div>
      <el-row>
        <el-col :span="8">
          <!-- 操作按钮 -->
          <div class="operation-div">
            <el-button type="primary" @click="onAdd">添加</el-button>
          </div>
        </el-col>
        <el-col :span="16">
          <!-- 条件查询 -->
          <div class="search-div">
            <el-form :inline="true" :model="searchData" class="demo-form-inline">
              <el-form-item label="用户名：">
                <el-input v-model="searchData.name" placeholder="请输入用户名" clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button type="primary" @click="onRest">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 表格内容 -->
    <div>
      <el-table :data="tableData" border stripe style="width: 100%" :header-cell-style="{ background: '#ECF5FF' }">
        <el-table-column type="index" :index="indexMethod" />
        <el-table-column prop="username" label="账号">
          <template #default="scope">
            <el-link @click="viewUserDetail(scope.row.userId)">{{ scope.row.username }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="fullName" label="全名" />
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="regionName" label="地区" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="margin-top: 20px">
        <el-pagination
          v-model:current-page="pageData.currentPage"
          v-model:page-size="pageData.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="->, jumper, total, sizes, prev, pager, next"
          :total="pageData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 添加修改对话框表单-->
  <el-dialog v-model="dialogFormVisible" :title="title" width="500" draggable overflow @close="onDialogFormCancel">
    <el-form :model="form" ref="ruleFormRef" :rules="rules">
      <el-form-item label="账号" prop="username">
        <el-input v-model="form.username" :disabled="!isAdd" />
      </el-form-item>
      <el-form-item label="密码" v-if="isAdd" prop="password">
        <el-input v-model="form.password" type="password" />
      </el-form-item>
      <el-form-item label="姓名" prop="fullName">
        <el-input v-model="form.fullName" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-input v-model="form.role" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-input v-model="form.status" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="地区" prop="regionName">
        <el-input v-model="form.regionName" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onDialogFormCancel">取消</el-button>
        <el-button type="primary" @click="onDialogFormConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from "vue";
import { addUsermainService, getUsermainById, updateUsermainService, deleteByIdmainService, pageListmainService , permission} from "@/api/user.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from 'vue-router';

// 表单数据
const searchData = ref({
  name: "",
});
// 表格数据
const tableData = ref([]);

/** 分页 */
// 分页数据
const pageData = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 20,
});
// 分页插件，每页条数发生改变时
const handleSizeChange = (val) => {
  pageData.pageSize = val;
  getPageList();
};
// 分页插件，当页码发生改变时
const handleCurrentChange = (val) => {
  pageData.currentPage = val;
  getPageList();
};

// 分页查询
const getPageList = async () => {
  const params = {
    currentPage: pageData.currentPage,
    pageSize: pageData.pageSize,
    //name: searchData.value.name,
  };
  const result = await pageListmainService(params);
  console.log(result + " test result")
  pageData.total = result.data.total;
  tableData.value = result.data.items;
};
getPageList();

// 头部表单函数定义
const onSearch = () => {
  getPageList();
};
// 重置查询表单
const onRest = () => {
  searchData.value = {};
  getPageList();
};

/** 添加修改对话框表单 */
const form = ref({
  username: '',
  password: '',
  fullName: '',
  phone: '',
  email: '',
  role: '',
  status: '',
  regionName: ''
});
// 重置对话框表单
const restForm = () => {
  form.value = {
    username: '',
    password: '',
    fullName: '',
    phone: '',
    email: '',
    role: '',
    status: '',
    regionName: ''
  };
  title.value = '添加用户';
  isAdd.value = true;
};
const title = ref('添加用户');
const isAdd = ref(true);
const dialogFormVisible = ref(false);

const router = useRouter();

const permissiona = async() =>{

  let a = await permission()
  //let result = await updateUsermainService(form.value);
  if(!a.data)
  {
    ElMessage.error("您没有权限");
  }
}
// 提交对话框表单按钮事件
const onDialogFormConfirm = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid) => {
    if (valid) {
      confirm();
    }
  });
};
// 取消对话表单框按钮事件
const onDialogFormCancel = () => {
  dialogFormVisible.value = false;
  restForm();
};

// 添加按钮事件
const onAdd = async () => {
  permissiona()
  let a = await permission()
  if(a.data)
  {
    title.value = '添加用户';
    isAdd.value = true;
     dialogFormVisible.value = true;
  }
}

// 修改按钮事件
const handleEdit = async (index, row) => {
  title.value = '修改用户';
  isAdd.value = false;
  permissiona()
  let a = await permission()
  if(a.data)
  {
    const id = { id: row.userId };
    let result = await getUsermainById(id);
    form.value = result.data;
    dialogFormVisible.value = true;
  }
};

// 删除按钮事件
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
    '确认要删除吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      permissiona()
      let a = await permission()
      if(a.data)
      {
        let result = await deleteByIdmainService(row.userId);
        ElMessage.success(result.msg ? result.msg : '删除成功');
        getPageList();
      }
    })
    .catch(() => {});
};

// 提交表单
const confirm = async () => {
  if (isAdd.value) {
    try {
      
      let result = await addUsermainService(form.value);
      ElMessage.success(result.msg ? result.msg : '添加成功');
      dialogFormVisible.value = false;
      restForm();
      getPageList();
    } catch (error) {}
  } else {
    try {
      let result = await updateUsermainService(form.value);
      ElMessage.success(result.msg ? result.msg : '修改成功');
      dialogFormVisible.value = false;
      restForm();
      getPageList();
    } catch (error) {}
  }
};

/** 表单校验 */
const ruleFormRef = ref(null);
const rules = ref({
  username: [{ required: true, message: '请输入账号名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  fullName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  role: [{ required: true, message: '请输入角色', trigger: 'blur' }],
  status: [{ required: true, message: '请输入状态', trigger: 'blur' }],
  phone: [{ required: true, trigger: 'blur', message: "请输入正确手机号", validator: checkPhone }]
});

// 手机号自定义校验
var checkPhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('手机号不能为空'));
  } else {
    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
    if (reg.test(value)) {
      callback();
    } else {
      return callback(new Error('请输入正确的手机号'));
    }
  }
};

// 查看用户详情
const viewUserDetail = (userId) => {
  router.push({ name: 'UserDetail', params: { userId } });
};
</script>

<style scoped>
.operation-div {
  width: 100%;
  text-align: left;
  padding-left: 10px;
  padding-top: 10px;
}

.search-div {
  width: 100%;
  text-align: right;
  padding-top: 10px;
}

.dialog-footer {
  text-align: right;
  padding: 10px 0;
}
</style>
